package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.jetbrains.annotations.NotNull;
import org.linlinjava.litemall.db.dao.LitemallMemberRuleMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMemberMapper;
import org.linlinjava.litemall.db.dao.UserMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LitemallUserService {
    @Resource
    private LitemallUserMapper litemallUserMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private LitemallMemberRuleMapper memberRuleMapper;
    @Resource
    private LitemallUserMemberMapper userMemberMapper;

    @Autowired
    private LitemallBalanceRecordService balanceRecordService;

    @Autowired
    private LitemallMemberTimesService litemallMemberTimesService;

    public LitemallUser findById(Integer userId) {
        return litemallUserMapper.selectByPrimaryKey(userId);
    }

    public UserVo findUserVoById(Integer userId) {
        LitemallUser user = findById(userId);
        UserVo userVo = new UserVo();
        userVo.setNickname(user.getNickname());
        userVo.setAvatar(user.getAvatar());
        return userVo;
    }

    public LitemallUser queryByOid(String openId) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andWeixinOpenidEqualTo(openId).andDeletedEqualTo(false);
        return litemallUserMapper.selectOneByExample(example);
    }

    public LitemallUser queryByUid(String unionId) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andWeixinUnionidEqualTo(unionId).andDeletedEqualTo(false);
        return litemallUserMapper.selectOneByExample(example);
    }

    public int add(LitemallUser user) {
        user.setAddTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return litemallUserMapper.insertSelective(user);
    }

    public int updateById(LitemallUser user) {
        user.setUpdateTime(LocalDateTime.now());
        return litemallUserMapper.updateByPrimaryKeySelective(user);
    }

    public int updateWithOptimisticLocker(LitemallUser user) {
        LocalDateTime preUpdateTime = user.getUpdateTime();
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateWithOptimisticLocker(preUpdateTime, user);
    }

    public List<UserNode> queryTeam(Integer userId) {
        return userMapper.queryTeam(userId);
    }

    /**
     * 增加余额
     *
     * @param userId
     * @param amount
     * @return null出错
     */
    public BigDecimal addBalance(Integer userId, BigDecimal amount, Short type) {
        LitemallUser user = findById(userId);
        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        if (user == null) {
            return null;
        }
        LitemallBalanceRecord record = new LitemallBalanceRecord();
        record.setBeforeAmount(user.getBalance());
        BigDecimal add = user.getBalance().add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (add.compareTo(BigDecimal.ZERO) < 0) {
            return null;
        }
        user.setBalance(add);
        updateWithOptimisticLocker(user);
        record.setAfterAmount(user.getBalance());
        record.setAmount(amount);
        record.setUserId(userId);
        record.setType(type);
        balanceRecordService.create(record);
        return add;
    }

    public List<LitemallUser> querySelective(String nickname, String mobile, Integer page, Integer size, String sort, String order) {
        LitemallUserExample example = new LitemallUserExample();
        LitemallUserExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(nickname)) {
            criteria.andNicknameLike("%" + nickname + "%");
        }
        if (!StringUtils.isEmpty(mobile)) {
            criteria.andMobileLikeTo("%" + mobile + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return litemallUserMapper.selectByExample(example);
    }

    public int count() {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andDeletedEqualTo(false);

        return (int) litemallUserMapper.countByExample(example);
    }

    public List<LitemallUser> queryByUsername(String username) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andUsernameEqualTo(username).andDeletedEqualTo(false);
        return litemallUserMapper.selectByExample(example);
    }

    public boolean checkByUsername(String username) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andUsernameEqualTo(username).andDeletedEqualTo(false);
        return litemallUserMapper.countByExample(example) != 0;
    }

    public List<LitemallUser> queryByMobile(String mobile) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andMobileEqualTo(mobile).andDeletedEqualTo(false);
        return litemallUserMapper.selectByExample(example);
    }

    public List<LitemallUser> queryByOpenid(String openid) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andWeixinOpenidEqualTo(openid).andDeletedEqualTo(false);
        return litemallUserMapper.selectByExample(example);
    }

    public void deleteById(Integer id) {
        litemallUserMapper.logicalDeleteByPrimaryKey(id);
    }

    public BigDecimal sumCostMoney() {
        return userMapper.sumCostMoney();
    }

    @Transactional
    public Map<String, String> makeOrdinaryUserToUserMember(Integer userId, Integer memberRoleId, String phoneNumber) {
        Map<String, String> map = new HashMap<>();
        // 验证会员信息入参
        LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(userId);
        if (litemallUser == null) {
            map.put("error", "509");
            map.put("errorDesc", "该用户不存在");
            return map;
        }
        LitemallUserMemberExample example = new LitemallUserMemberExample();
        example.createCriteria().andUserIdEqualTo(litemallUser.getId()).andDeletedEqualTo(false);

        //userMemberMapper.selectOneByExample(example);
        List<LitemallUserMember> litemallUserMembers = userMemberMapper.selectByExample(example);
        if (litemallUserMembers != null && litemallUserMembers.size() > 0) {
            map.put("error", "509");
            map.put("errorDesc", "该用户已是会员");
            return map;
        }

        //验证会员类型入参
        LitemallMemberRule litemallMemberRule = memberRuleMapper.selectByPrimaryKey(memberRoleId);
        if (litemallMemberRule == null) {
            map.put("error", "509");
            map.put("errorDesc", "无该类型会员");
            return map;
        }
        litemallUser.setUserLevel(2);
        litemallUser.setCostMoney(litemallUser.getCostMoney().add(litemallMemberRule.getMemberAmount()));
        litemallUser.setMobile(phoneNumber);
        this.updateById(litemallUser);

        LitemallUserMember userMember = new LitemallUserMember();
        userMember.setUserId(litemallUser.getId());
        userMember.setMemberRuleId(litemallMemberRule.getId());
        userMember.setMemberRuleName(litemallMemberRule.getMemberName());
        userMember.setNickname(litemallUser.getNickname());
        userMember.setExpirationTime(LocalDateTime.now().plusDays(litemallMemberRule.getMemberDuration()));
        userMember.setAddTime(LocalDateTime.now());
        userMember.setEffective("1");
        userMember.setUpdateTime(LocalDateTime.now());
        userMemberMapper.insertSelective(userMember);


        if (litemallMemberRule.getMemberType() == 0) {
            LitemallMemberTimes memberTimes = getLitemallMemberTimes(userMember.getUserId(), litemallMemberRule, Long.valueOf(userMember.getId()));
            litemallMemberTimesService.insertMemberTimes(memberTimes);
        }
        map.put("error", "200");
        map.put("errorDesc", "成功");
        return map;
    }


    @NotNull
    private LitemallMemberTimes getLitemallMemberTimes(Integer userId, LitemallMemberRule memberRule, Long memberId) {
        LitemallMemberTimes memberTimes = new LitemallMemberTimes();
        memberTimes.setUserId(Long.valueOf(userId));
        memberTimes.setMemberId(Long.valueOf(memberRule.getId()));
        memberTimes.setAllTimes(memberRule.getMemberDuration());
        memberTimes.setUseTimes(0);
        memberTimes.setNotUsedTimes(memberTimes.getAllTimes());
        memberTimes.setIsEffective("1");
        memberTimes.setIsDel("0");
        memberTimes.setOrderId(Long.valueOf(memberId));
        return memberTimes;
    }
}
